﻿using System;
using System.Diagnostics;
using System.Linq;

using Microsoft.Practices.EnterpriseLibrary.Logging;

using TraceView.Shared;

namespace TraceView.Listeners.EntLib31
{
    internal static class Utilities
    {
        public static Severity ConvertEnum(this TraceEventType eventType)
        {
            switch (eventType)
            {
                case TraceEventType.Critical:
                    return Severity.Critical;
                case TraceEventType.Error:
                    return Severity.Error;
                case TraceEventType.Information:
                    return Severity.Information;
                case TraceEventType.Warning:
                    return Severity.Warning;
                case TraceEventType.Verbose:
                    return Severity.Verbose;
                default:
                    return Severity.Information;
            }
        }

        public static TraceData ToTraceData(this LogEntry logEntry, RegisteredTraceHandler traceHandler = null)
        {
            var traceData = new TraceData();
            if (logEntry.Categories != null)
                foreach (string category in logEntry.Categories)
                {
                    traceData.Categories.Add(category);
                }
            traceData.Severity = logEntry.Severity.ConvertEnum();
            traceData.Source = logEntry.MachineName;
            traceData.TimeStamp = logEntry.TimeStamp;
            traceData.UserName = Environment.UserName;
            //TODO
            traceData.ApplicationName = logEntry.AppDomainName.Split('.')[0].ToLower();
            if (traceHandler != null)
                traceData.TraceObject = traceHandler.Handler.Serialize(logEntry.ExtendedProperties);

            return traceData;
        }
    }
}